// @charset "utf-8";

define(function(require, exports, module) {
	var publicMethod = require('../../public/public'),
		clientApi = require('../../public/clientapi');

	var IndexBase  = require('../allindex/indexbase');
	var explainChart = require('./ztchart');

	function QrpjModule () {
		this.domId = 'qrpj';
		this.MODULENAME = '强弱评级';
		this.EXPLAINTEXT = '实时提示两市个股涨跌停的数量。涨跌停数量反应了短期市场的强弱，涨停个股越多，市场越强；反之需警惕市场走弱。';

		this.type = 'min';

		// this.code = '883900,1A0001';
		// this.indexCode = '883900';
		this.hcType = 'qrpjhc';

		this.latestVal1 = '--';
		this.latestVal2 = '--';
		this.latestVal3 = '--';

		this.beginDate = '';

		this.HighchartsObj = null;
		this.renderDom();
	}

	publicMethod.extendClass(QrpjModule, IndexBase);

	QrpjModule.prototype.renderDom = function () {
		var self = this;
		var htmlDom = '<li data-mname="'+ self.domId +'">' +
					'<div class="module-item">' +
						'<div class="module-header">' +
							'<a href="###" class="icon module-close-btn"></a>' +
							'<div class="date-wrap">' +
								'<p class="date-wrap-single">' +
									'<input type="text" class="icon date-picker" value="2017-02-16" id="'+ self.domId + 'DatePicker" />' +
									'<a href="###" class="icon interval-btn" title="切换区间" id="'+ self.domId + 'IntervalBtn"></a>' +
								'</p>' +
								'<p class="date-wrap-interval hide">' +
									'<input type="text" class="icon date-picker" value="2017-02-16" id="'+ self.domId + 'SDatePicker" />' +
									'<i class="separator">-</i>' +
									'<input type="text" class="icon date-picker" value="2017-02-16" id="'+ self.domId + 'EDatePicker"  />' +
									'<a href="###" class="icon single-btn" title="切换区间" id="'+ self.domId + 'SingleBtn"></a>' +
								'</p>' +
							'</div>' +
							'<p class="module-name">'+ self.MODULENAME +'</p><i class="icon module-tip-btn" id="'+ self.domId +'ExplainBtn"><b class="icon"></b></i>' +
						'</div>' +
						'<div class="module-main">' +
							'<div class="chart-box" id="'+ self.domId +'ChartBox">' +
							'</div>' +
							'<div class="explain-box hide" id="'+ self.domId +'ExplainBox">' +
								'<p class="explain-text">'+ self.EXPLAINTEXT +'</p>' +
								'<div class="clearfix">' +
								'<div class="explain-left '+ self.domId +'-explain-pic">' +
								'</div>' +
								'<div class="explain-right">' +
									'<p>今日解读：<span id="'+ self.domId +'ExplainData">放量净流入12亿</span></p>' +
									'<br/>' +
									'<p>上涨概率回测</p>' +
									'<p id="'+ self.hcType +'HcData">历史数据回测中...</p>' +
								'</div>' +
								'</div>' +
							'</div>' +
							'<p class="non-trade-tip" id="'+ self.domId +'NonTradeTip">非交易日，请重新选择</p>' +
						'</div>' +
					'</div>' +
				'</li>';
				$('#modules-list-ul').append(htmlDom);
				self.renderData();

				self.bindEvents();
	}
	QrpjModule.prototype.renderData = function () {
		var tradeDay = clientApi.getTradingDay();

		this.requestMinData(tradeDay);

	}
	QrpjModule.prototype.requestMinData = function (date) {
		var self = this;
		self.beginDate = date;
		publicMethod.ajaxJsonp({
			url: 'http://hqstats.10jqka.com.cn/fyzzt.php?date=' + date,
			jsonpCallback: 'fyzzt',
			callback: function(result) {
				self.analyticalData(result);
			}
		});

		this.getExplainData(date);
	}
	QrpjModule.prototype.requestDayData = function (sdate, edate) {
		var self = this;
		publicMethod.ajaxJsonp({
			url: 'http://hqstats.10jqka.com.cn/fyzzt.php?begin=' + sdate + '&end=' + edate,
			jsonpCallback: 'fyzzt',
			callback: function(result) {
				self.analyticalData(result);
			}
		});
	}
	QrpjModule.prototype.getExplainData = function (date) {
		var hour = clientApi.serverHour();

		if (hour > 0945) {
			this.requestZxData(this.hcType, date);
		} else {
			this.renderRisingProb(this.hcType, '');
		}
	}
	QrpjModule.prototype.bindEvents = function () {
		var self = this;
		var tradeDay = clientApi.getTradingDay();

		var minDate = '2016-01-04';

		this.datePicker(tradeDay, this.domId, function (date) {
			self.requestMinData(date);
		}, function (sdate, edate) {
			self.requestDayData(sdate, edate);
		}, minDate);

		var hoverTimer;
		$('#'+ self.domId + 'ExplainBtn').hover(function () {
			var _this = this;
			hoverTimer = setTimeout(function () {
				$(_this).find('b').show();
            	$(_this).parents('.module-item').find('.explain-box').show();
			}, 1000)
		}, function () {
			clearTimeout(hoverTimer);
		});

		$('#'+ self.domId +'ExplainBox').mouseleave(function () {
			$(this).parents('.module-item').find('b.icon').hide();
			$(this).hide();
		});
	}
	QrpjModule.prototype.analyticalData = function (result, isUpdate) {
		var self = this;
		var ztData = [],
			dtData = [],
			fyzData = [],
			dateArr = [],
			ztNewestData = '--',
			dtNewestData = '--',
			fyzNewestData = '--';
		if (!$.isEmptyObject(result)) {
			if (self.type == 'min') {
				$.each(result.data, function (i, val) {
					ztData.push(val.zt);
					dtData.push(val.dt);
					fyzData.push(val.fyzzt);
				});
				$('#'+ self.domId +'ExplainBtn').show();
			} else {
				$.each(result, function(j, value) {
					dateArr.push(j.substr(4, 2) + '-' + j.substr(6));
					ztData.push(value.zt);
					dtData.push(value.dt);
					fyzData.push(value.fyzzt);
				});
				$('#'+ self.domId +'ExplainBtn').hide();
			}
			ztNewestData = ztData[ztData.length - 1];
			dtNewestData = dtData[dtData.length - 1];
			fyzNewestData = fyzData[fyzData.length - 1];
			self.latestVal1 = ztNewestData;
			self.latestVal2 = dtNewestData;
			self.latestVal3 = fyzNewestData;
		} else {
			$('#'+ self.domId +'ExplainBtn').hide();
		}
		self.renderExplain(ztNewestData);

		if (isUpdate && self.HighchartsObj) {

			self.HighchartsObj.series[0].update({
				data: ztData
			});
			self.HighchartsObj.series[1].update({
				data: dtData
			});
			self.HighchartsObj.series[2].update({
				data: fyzData
			});

			$('.zt-legend').text(self.latestVal1);
			$('.dt-legend').text(self.latestVal2);
			$('.fyz-legend').text(self.latestVal3);
		} else {
			self.drawChart(ztData, dtData, fyzData, dateArr);
		}
	}

	QrpjModule.prototype.renderExplain = function (data) {
		var self = this;
		if (isNaN(data)) {
			$('#'+ self.domId +'ExplainData').text(self.MODULENAME + '：--');
			return;
		}
		var gradeTxt = '--';
		var curTime = clientApi.serverTime(),
			curHour = clientApi.serverHour();
		var grade1 = 80,
			grade2 = 50,
			grade3 = 30;
		if (curTime == self.beginDate && curHour < 1000) {
			grade1 = 40;
			grade2 = 25;
			grade3 = 15;
		} else if (curTime == self.beginDate && curHour < 1300) {
			grade1 = 60;
			grade2 = 40;
			grade3 = 25;
		}
		if (data > grade1) {
			gradeTxt = '强';
		} else if (data > grade2 && data <= grade1) {
			gradeTxt = '较强';
		} else if (data > grade3 && data <= grade2) {
			gradeTxt = '中性';
		} else if (data <= grade3) {
			gradeTxt = '弱';
		}

		$('#'+ self.domId +'ExplainData').text(self.MODULENAME + '表现' + gradeTxt);
		explainChart.renderChart(data);
	}

	QrpjModule.prototype.drawChart = function (series1,series2,series3, dateArr) {
		var self = this;
		var _tickPositions = [0, 120, 241],
			_tickInterval = '120',
			_xAxisMin = '0',
			_xAxisMax = '241',
			_xAxisData = publicMethod.xAxisData;

		if (self.type == 'day') {
			_tickPositions = null;
			_tickInterval = Math.ceil(dateArr.length / 10);
			_xAxisMin = null,
			_xAxisMax = null,
			_xAxisData = dateArr;
		}
		var chartOptions = {
			credits: {
				enabled: false
			},
			title: {
				text: ''
			},
			chart: {
				backgroundColor: null,
				style: {
					"fontFamily": "Arial, \"Microsoft yahei\", Verdana, Helvetica, sans-serif",
					"fontSize": "12px"
				},
				marginTop: 40,
				marginLeft: 40,
				marginBottom: 30
			},
			series: [{
				name: '非一字涨停',
				type: 'line',
				color: '#efefef',
				lineWidth: 1,
				marker: {
					enabled: false,
					states: {
						hover: {
							fillColor: '#efefef',
							radius: 2,
							lineColor: 'rgba(200, 200, 200, 1)',
							lineWidthPlus: 1
						}
					}
				},
				data: series3
			}, {
				name: '涨停',
				type: 'line',
				color: '#ff3232',
				lineWidth: 1,
				marker: {
					enabled: false,
					states: {
						hover: {
							fillColor: '#ff3232',
							radius: 2,
							lineColor: 'rgba(255, 255, 255, 1)',
							lineWidthPlus: 1
						}
					}
				},
				data: series1
			}, {
				name: '跌停',
				type: 'line',
				color: '#00e600',
				lineWidth: 1,
				marker: {
					enabled: false,
					states: {
						hover: {
							fillColor: '#2aaa2a',
							radius: 2,
							lineColor: 'rgba(255, 255, 255, 1)',
							lineWidthPlus: 1
						}
					}
				},
				data: series2
			}],
			plotOptions: {
				series: {
					stickyTracking: false,
					events: {
						legendItemClick: function() {
							if (this.name == '非一字涨停') {
								clientApi.openUrlWeb(self.fyzztUrl, 4);
							} else if (this.name == '涨停') {
								clientApi.openUrlWeb(self.ztUrl, 4);
							} else if (this.name == '跌停') {
								clientApi.openUrlWeb(self.dtUrl, 4);
							}
							return false;
						}
					}
				},
				line: {
					states: {
						hover: {
							lineWidthPlus: 0
						}
					}
				}
			},
			xAxis: {
				lineWidth: 1,
				tickLength: 4,
				lineColor: '#808080',
				tickColor: '#808080',
				tickInterval: _tickInterval,
				tickPositions: _tickPositions,
				title: {
					text: ''
				},
				categories: _xAxisData,
				gridLineWidth: 0,
				labels: {
					align: 'center',
					rotation: 0,
					style: {
						color: '#afafaf'
					}
				},
				min: _xAxisMin,
				max: _xAxisMax
			},
			yAxis: {
				allowDecimals: false,
				lineWidth: 1,
				tickColor: '#808080',
				tickPosition: 'outside',
				gridLineWidth: 0,
				tickLength: 4,
				tickWidth: 1,
				title: {
					text: ''
				},
				lineColor: '#808080',
				labels: {
					// format: '{value}%',
					style: {
						color: '#afafaf'
					},
					x: -7
				}
			},
			legend: {
				align: 'right',
				verticalAlign: 'top',
				floating: false,
				symbolHeight: 10,
				symbolWidth: 14,
				itemStyle: {
					color: '#dedede',
					fontFamily: 'Microsoft yahei',
					fontWeight: 'normal'
				},
				itemHiddenStyle: {},
				itemHoverStyle: {
					color: '#bbb'
				},
				useHTML: true,
				labelFormatter: function() {
					if (this.name === '涨停') {
						return '<a href="###" title="包括ST股 沪深A股" class="textline"><span class="legend-item">涨停 <i class="zt-legend">' + self.latestVal1 + '</i></span></a>';
					}
					if (this.name === '跌停') {
						return '<span class="legend-item textline">跌停 <i class="dt-legend">' + self.latestVal2 + '</i></span>';
					}
					if (this.name === '非一字涨停') {
						return '<span class="legend-item textline">非一字涨停 <i class="fyz-legend">' + self.latestVal3 + '</i></span>';
					}
				}
			},
			tooltip: {
				shared: true,
				backgroundColor: '#2e3339',
				borderColor: '#505458',
				shape: '',
				crosshairs: [{
					width: 1,
					color: '#afafaf'
				}],
				// valueDecimals: 2,
				// valueSuffix: '%',
				style: {
					fontFamily: 'Microsoft yahei',
					color: '#fff'
				}
			}
		};

		$('#'+ self.domId +'ChartBox').highcharts(chartOptions);
		self.HighchartsObj = $('#'+ self.domId +'ChartBox').highcharts();
	}

	QrpjModule.prototype.updateSeries = function (isHasOverall, date, result) {
		var self = this;
		if (isHasOverall) {
			return;
		}
		var inputDate = $('#'+ self.domId + 'DatePicker').val();
		var isToday = inputDate.replace(/-/g, '') == date;

		if (this.type == 'min' && isToday) {
			if (result) {
				self.analyticalData(result, 'isUpdate');
				// self.getExplainData(date);
			} else {
				self.requestMinData(date);
				// self.getExplainData(date);
			}
		}
	}

	module.exports = QrpjModule;
});